package com.example.fashionshoes.interceptor;


import com.example.fashionshoes.constant.JwtConst;
import com.example.fashionshoes.utils.JwtUtil;
import com.example.fashionshoes.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(JwtConst.AUTH);
        try {
            Map<String, Object> map = JwtUtil.parseToken(token);
            Integer userId = (Integer) map.get(JwtConst.USER_ID);
            ThreadLocalUtil.set(map);
            //判断redis中的token与用户token是否相同
            String catchToken = stringRedisTemplate.opsForValue().get(JwtConst.USER_TOKEN_CATCH + userId);
            if (null == catchToken || !catchToken.equals(token)) {
                response.setStatus(401);
                return false;
            }
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
